'use strict';

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

var app = angular.module("myApp", ['ui.bootstrap', 'ui.bootstrap.datetimepicker']);

app.controller("diagnosisController", ['$scope', '$window', '$interval', function ($scope, $window, $interval) {
    $scope.toJSON = function (val) {
        return toJSON(val);
    };

    $scope.inCheckList = function (signal) {
        return $scope.faultMatched.filter(function (fault) {
            return fault != null && fault.checked;
        }).some(function (fault) {
            return fault.channels.some(function (channel) {
                return channel.id == signal.portId;
            });
        });
    };

    $scope.withUnknown = function (fault) {
        return fault != null && (fault.isMatched || $scope.showUnknown && fault.isUnknown);
    };

    $scope.timeClick = function ($event) {
        $event.preventDefault();
        $event.stopPropagation();
    };

    $scope.timeChanged = function ($event) {
        console.info($event.target);
    };

    $scope.toTimestamp = function () {
        $scope.dt.setTime($scope.t_timestamp);

        refreshSignals();
    };

    $scope.onTimeSet = function (newDate, oldDate) {
        $scope.status.isopen = !$scope.status.isopen;
        $scope.t_timestamp = $scope.dt.getTime();

        refreshSignals();
    };

    function refreshSignals() {
        $.get('http://' + window.location.hostname + ':' + window.basePort + '/rest/work/last/signal/' + $scope.dt.getTime(), function (data) {
            $scope.signals = data;
            $scope.$apply();
        });
    }

    $scope.status = {
        isopen: false
    };

    $scope.dt = new Date();
    $scope.isCollapsed2 = false;
    $scope.showUnknown = false;
    $scope.faultCheck = {};
    $scope.faultMatched = [];

    $scope.$watch('isCollapsed2', function () {
        $scope.diagnoiseAgain();
    }, true);

    $scope.diagnoiseAgain = function () {
        refreshSignals();
        $.post('http://' + window.location.hostname + ':' + window.basePort + '/rest/work/kg/match/' + $scope.dt.getTime(), {
            content: JSON.stringify($scope.manmalSignals)
        }, function (data) {
            $scope.matchedResult = data;
            var lastCheck = {};
            $scope.faultMatched.forEach(function (f) {
                lastCheck[f.id] = f.checked;
            });
            $scope.faultMatched = data.map(function (f) {
                f.checked = lastCheck[f.id] || false;
                return f;
            });
            $scope.$apply();
        });
    };

    function showToReport(faultId, filename, title) {
        var result = $scope.matchedResult.filter(function (res) {
            return res.id == faultId;
        })[0];
        var matchedNodes = void 0,
            unknownNodes = void 0,
            channels = void 0;
        if (result != null) matchedNodes = angular.toJson(result["matched"], false);else matchedNodes = "[]";

        if (result != null) unknownNodes = angular.toJson(result["unknown"], false);else unknownNodes = "[]";

        if (result != null) {
            var channelList = result["channels"].map(function (ch) {
                var value = _.find($scope.signals, function (port) {
                    return port.portId == ch.id;
                }).value;
                ch.value = value;
                return ch;
            });

            $scope.manmalSignals.filter(function (s) {
                return s.faultName == result.faultName;
            }).forEach(function (signal) {
                channelList.push({
                    name: signal.type == "manual" ? "(人工)" + signal.description : '(' + (signal.component == null ? "机组" : signal.component.name) + ')' + signal.featureType,
                    value: JSON.parse(signal.value)
                });
            });
            channels = angular.toJson(channelList, false);
        } else {
            channels = "[]";
        }

        var jumpTo = filename + '?faultId=' + faultId + '&matchedNodes=' + encodeURI(matchedNodes) + '&unknownNodes=' + encodeURI(unknownNodes) + '&timestamp=' + $scope.dt.getTime() + '&last_timestamp=' + result.last_timestamp + '&channels=' + encodeURI(channels);
        if (isInFrame()) {
            pushUrl('../fault/' + jumpTo, title);
        } else {
            $window.open(jumpTo);
        }
    }

    $scope.showFaultReport = function (faultId) {
        showToReport(faultId, "report.html", "诊断报告");
    };

    $scope.showFaultTree = function (faultId) {
        showToReport(faultId, "FaultExplain.html", "诊断解释");
    };

    $scope.manmalSignals = [];
    $scope.jumpToHuman = function (fid) {
        var result = $scope.matchedResult.filter(function (res) {
            return res.id == fid;
        })[0];
        if (result != null) {
            var featureToID = function featureToID(isAuto, f, cp) {
                if (isAuto) {
                    return "A&" + f.name + "&" + (cp == null ? 'NoC' : cp.id);
                } else {
                    return "M" + f.id;
                }
            };

            var signalToID = function signalToID(s) {
                if (s.type == "manual") {
                    return "M" + s.id;
                } else {
                    return "A&" + s.featureType + "&" + (s.component == null ? 'NoC' : s.component.id);
                }
            };

            var unknownNodes = result["unknown"];

            Graph.loadGraph(fid, function (g) {
                var features = [].concat(_toConsumableArray(g.nodes.values())).filter(function (node) {
                    return node.$type == "Feature" && unknownNodes.some(function (uid) {
                        return uid == node.id;
                    });
                });
                var fault = g.getRoot();
                var manS = new Map($scope.manmalSignals.map(function (s) {
                    return [signalToID(s), s];
                }));
                features.forEach(function (f) {
                    var isAuto = f.type.contains("auto");
                    var fx = FeatureNode.features.filter(function (feature) {
                        return feature.id == f.id;
                    });
                    var cp = null;
                    if (fx != null && fx.length > 0 && fx[0].components != null && fx[0].components.length != 0) {
                        var id = fx[0].components[0];
                        var cx = [].concat(_toConsumableArray(g.nodes.values())).filter(function (c) {
                            return c.id == id;
                        });
                        if (cx != null && cx.length > 0) {
                            cp = {
                                id: id,
                                name: cx[0].name
                            };
                        }
                    }
                    manS.set(featureToID(isAuto, f, cp), {
                        id: f.id,
                        faultName: fault.name,
                        type: isAuto ? "auto" : "manual",
                        description: f.description,
                        featureType: f.name,
                        value: isAuto ? "[0]" : "unknown",
                        component: cp
                    });
                });
                $scope.manmalSignals = [].concat(_toConsumableArray(manS.values()));
                $scope.$apply();
            });
        }
        // alert("补充条件！！！");
    };

    $scope.deleteManualSignal = function (manualSignalId) {
        for (var i = 0; i < $scope.manmalSignals.length; i++) {
            var manalSignal = $scope.manmalSignals[i];
            if (manalSignal.id == manualSignalId) {
                $scope.manmalSignals.splice(i, 1);
                return;
            }
        }
    };
}]);

app.filter('startX', [function () {
    return function (array, size) {
        if (array.length <= size) return array.map(function (x) {
            return x.toFixed(2);
        }).join(",");
        return array.slice(0, 2).map(function (x) {
            return x.toFixed(2);
        }).join(",") + "等" + array.length + "项";
    };
}]);

var toJSON = function toJSON(obj) {
    var cache = [];
    return JSON.stringify(obj, function (key, value) {
        if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && value !== null) {
            if (cache.indexOf(value) !== -1) {
                // Circular reference found, discard key
                return;
            }
            // Store value in our collection
            cache.push(value);
        }
        return value;
    });
};

var isInFrame = function isInFrame() {
    return localStorage.getItem("useInFrame") == "true";
};

var pushUrl = function pushUrl(url, title) {
    var stackStr = localStorage.getItem("tabStack") || "[]";
    var stack = JSON.parse(stackStr);
    stack.push({
        url: url,
        title: title
    });
    stackStr = JSON.stringify(stack);
    localStorage.setItem("tabStack", stackStr);
};

FeatureNode.loadFeatures();
